//
//  TTDetailFilterViewController.m
//  TaoTuo
//
//  Created by admin on 2019/8/28.
//  Copyright © 2019 admin. All rights reserved.
//

#import "TTDetailFilterViewController.h"
#import "TTDetailFilterExistView.h"
#import "TTDetailFliterCustomView.h"
#import "TTGoodsDetailViewController.h"
#import "TTDetailFilterDingzhiView.h"

@interface TTDetailFilterViewController ()
{
    CGFloat h;
    CGFloat top;
    CGFloat viewH;
}

@property (nonatomic, strong) TTDetailModel *model;
@property (nonatomic, strong) UIButton *existBtn;   // 现货按钮
@property (nonatomic, strong) UIButton *customBtn;   // 下单按钮
@property (nonatomic, strong) UIButton *dingzhiBtn;   // 定制按钮
@property (nonatomic, strong) TTDetailFilterExistView *existView;
@property (nonatomic, strong) TTDetailFliterCustomView *customView;
@property (nonatomic, strong) TTDetailFilterDingzhiView *dingzhiView;
@property (nonatomic, strong) UIView *footerView;
@property (nonatomic, strong) UIButton *confirmBtn;

///记录刚进来时选中的商品
@property (nonatomic, strong) NSMutableDictionary *existViewSelectDic;

//@property (nonatomic, strong) TTDetailFilterHeaderView *headerView;
//@property (nonatomic, strong) UITableView *tableView;
//@property (nonatomic, strong) NSMutableArray *dataArray;
//@property (nonatomic, strong) NSMutableArray *selectArray;  // 已选中的
/// 有多少可下单的产品
@property (nonatomic, assign) NSInteger customCount;
///根据条件过滤掉的数量
@property (nonatomic, assign) int stockFilterCount;

@property (nonatomic, strong) UIView *yellowView;

@end

@implementation TTDetailFilterViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    
    h = self.view.height * 0.85;
    viewH = h - 45 - Tabbar_Bottom_height;
    
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(dismiss) name:detailFilterViewControllerDismiss object:nil];
    
}


- (void)dismiss
{
    for (TTDetailStockListModel *model in self.existView.selectArray) {
        model.selected = NO;
    }
    for (TTDetailStockListModel *model in self.customView.selectArray) {
        model.selected = NO;
    }
    
    for (NSString *key in self.existViewSelectDic.allKeys) {
        TTDetailStockListModel *model = self.existViewSelectDic[key];
        model.selected = YES;
    }
    
    [self dismissViewControllerAnimated:YES completion:nil];
}


- (void)setModel:(TTDetailModel *)model datasArray:(NSArray *)datasArray selectArray:(nonnull NSArray *)selectArray customCount:(NSInteger)customCount stockFilterCount:(int)stockFilterCount
{
    self.model = model;
    self.customCount = customCount;
    self.stockFilterCount = stockFilterCount;
    
    [self setCellContentWithModel:model dataArray:datasArray];
    
    [self setupSubviewsWithDatasArray:datasArray selectArray:selectArray];
    // 添加选中的
    [self.existViewSelectDic removeAllObjects];
    [self.existView.selectArray removeAllObjects];
    for (TTDetailStockListModel *model in selectArray) {
        if (model.selected && model.StockType == 0) {
            [self.existView.selectArray addObject:model];
            [self.existViewSelectDic setObject:model forKey:model.GoodsBarCode];
        }
    }
    
}

- (void)setCellContentWithModel:(TTDetailModel *)model dataArray:(NSArray *)dataArray
{
    for (TTDetailStockListModel *slModel in dataArray) {
        // 行间距
        NSString *contentStr = [slModel.GoodsAttr componentsJoinedByString:@"\n"];
        NSMutableAttributedString *contentAttr = [[NSMutableAttributedString alloc] initWithString:contentStr];
        NSMutableParagraphStyle *style = [[NSMutableParagraphStyle alloc] init];
        style.lineSpacing = 5;
        [contentAttr addAttribute:NSParagraphStyleAttributeName value:style range:NSMakeRange(0, contentStr.length)];
//        CGFloat contentW = SCREEN_WIDTH >= 375 ? 290 * kScale : 270 * kScale;
        CGFloat contentW = SCREEN_WIDTH - 15;
        CGFloat h = [contentStr boundingRectWithSize:CGSizeMake(contentW, MAXFLOAT) options:NSStringDrawingUsesLineFragmentOrigin attributes:@{NSFontAttributeName : [UIFont systemFontOfSize:12], NSParagraphStyleAttributeName : style} context:nil].size.height + 20 + 20;
        slModel.h = h;
    }
}


// 确定按钮点击了
- (void)confirmBtnClick
{
    
    NSMutableArray *allSelectedArray = [NSMutableArray array];
    
    BOOL canClick = NO;
    for (TTDetailStockListModel *model in self.existView.selectArray) {
        if (model.selected) {
            canClick = YES;
            model.selected = YES;
            [allSelectedArray addObject:model];
        }
    }
    
    for (TTDetailStockListModel *model in self.customView.selectArray) {
        if (model.selected) {
            canClick = YES;
            model.selected = YES;
            [allSelectedArray addObject:model];
        }
    }
    
    if ([self.confirmBtn.titleLabel.text isEqualToString:@"提交"]) {
        
        if ([self.dingzhiView canCommit]) {
            // 提交定制
            [self confirmCustomData];
        }
        
        if (allSelectedArray.count > 0) {
            if (self.selectCompleteBlock) {
                self.selectCompleteBlock(allSelectedArray);
            }
        }
        
    } else {
        if (!canClick) {
            [self.view makeToast:@"请选择货品" duration:1.0 position:CSToastPositionCenter];
            return;
        }
        
        if (self.selectCompleteBlock) {
            self.selectCompleteBlock(allSelectedArray);
        }
        
        [self dismissViewControllerAnimated:YES completion:nil];
    }
    
    
    
}


- (void)confirmCustomData
{
    [self.dingzhiView.dic setObject:self.dingzhiView.tf.text forKey:@"param.lettering"];
    [self.dingzhiView.dic setObject:self.dingzhiView.textView.text forKey:@"param.content"];
    [self.dingzhiView.dic setObject:self.styleLibraryId forKey:@"param.styleLibraryId"];
    
    @weakify(self)
    [[LLNetworkManagerTool sharedManager] postUrlString:addCustomData_api parameters:self.dingzhiView.dic success:^(NSURLSessionDataTask * _Nonnull task, id  _Nullable responseObject) {
        @strongify(self)
        
        [MBProgressHUD showSuccess:@"提交成功"];
        
        [self dismissViewControllerAnimated:YES completion:nil];
        
    } failure:^(NSURLSessionDataTask * _Nonnull task, NSError * _Nullable error) {
        
    } showLoadingInView:self.view];
}


///点击现货
- (void)existBtnClick:(UIButton *)sender
{
    [self.confirmBtn setTitle:@"确定" forState:UIControlStateNormal];
    
    if (!self.allShopShow) {
        self.yellowView.hidden = self.stockFilterCount == 0;
        if (!self.yellowView.hidden) {
            self.footerView.frame = CGRectMake(0, h - 75 - Tabbar_Bottom_height, self.view.width, 75 + Tabbar_Bottom_height);
            self.confirmBtn.top = self.yellowView.bottom;
        }
    }
    
    sender.backgroundColor = [UIColor whiteColor];
    self.customBtn.backgroundColor = UIColorHex(EDEDED);
    self.dingzhiBtn.backgroundColor = UIColorHex(EDEDED);
    self.existView.hidden = NO;
    
    CGFloat hh = self->viewH - self->top;
    [UIView animateWithDuration:0.2 animations:^{
        self.existView.frame = CGRectMake(0, self->top, self.view.width, hh);
        self.customView.frame = CGRectMake(self.view.width, self->top, self.view.width, hh);
        CGFloat left = self.customView ? self.customView.right : self.existView.right;
        self.dingzhiView.frame = CGRectMake(left, self->top, self.view.width, hh);
    } completion:^(BOOL finished) {
        self.customView.hidden = YES;
        self.dingzhiView.hidden = YES;
    }];
    
}

///点击下单
- (void)customBtnClick:(UIButton *)sender
{
    [self.confirmBtn setTitle:@"确定" forState:UIControlStateNormal];
    
    self.yellowView.hidden = YES;
    self.footerView.frame = CGRectMake(0, viewH, self.view.width, 45 + Tabbar_Bottom_height);
    self.confirmBtn.top = 0;
    
    sender.backgroundColor = [UIColor whiteColor];
    self.existBtn.backgroundColor = UIColorHex(EDEDED);
    self.dingzhiBtn.backgroundColor = UIColorHex(EDEDED);
    self.customView.hidden = NO;
    
    CGFloat hh = self->viewH - self->top;
    [UIView animateWithDuration:0.2 animations:^{
        
        self.customView.frame = CGRectMake(0, self->top, self.view.width, hh);
        self.existView.frame = CGRectMake(-self.view.width, self->top, self.view.width, hh);
        
        self.dingzhiView.frame = CGRectMake(self.customView.right, self->top, self.view.width, hh);
    } completion:^(BOOL finished) {
        self.existView.hidden = YES;
        self.dingzhiView.hidden = YES;
    }];
    
}

/// 点击定制
- (void)dingzhiBtnClick:(UIButton *)sender
{
    [self.confirmBtn setTitle:@"提交" forState:UIControlStateNormal];
    
    self.yellowView.hidden = YES;
    self.footerView.frame = CGRectMake(0, viewH, self.view.width, 45 + Tabbar_Bottom_height);
    self.confirmBtn.top = 0;
    
    sender.backgroundColor = [UIColor whiteColor];
    self.existBtn.backgroundColor = UIColorHex(EDEDED);
    self.customBtn.backgroundColor = UIColorHex(EDEDED);
    self.dingzhiView.hidden = NO;
    
    CGFloat hh = self->viewH - self->top;
    [UIView animateWithDuration:0.2 animations:^{
        self.existView.frame = CGRectMake(-self.view.width * 2, self->top, self.view.width, hh);
        self.customView.frame = CGRectMake(-self.view.width, self->top, self.view.width, hh);
        self.dingzhiView.frame = CGRectMake(0, self->top, self.view.width, hh);
    } completion:^(BOOL finished) {
        self.existView.hidden = YES;
        self.customView.hidden = YES;
    }];
}

///显示所有商品
- (void)showAllShopAction:(UIButton *)sender
{
    self.allShopShow = YES;
    [MBProgressHUD showLoadingAnimationOnView:[UIApplication sharedApplication].keyWindow];
    @weakify(self)
    self.detailVC.lookAllGuigeData = YES;
    [self.detailVC getNetworkDataSuccessBlock:^(TTDetailModel * _Nonnull model, NSArray * _Nonnull canShowGuigeArray, NSArray * _Nonnull guigeArray, NSInteger customizedCount, int stockFilterCount) {
        @strongify(self)
        [MBProgressHUD dismissAnimationOnView:[UIApplication sharedApplication].keyWindow];
        [self setModel:model datasArray:canShowGuigeArray selectArray:guigeArray customCount:customizedCount stockFilterCount:stockFilterCount];
    }];
}


- (void)setupSubviewsWithDatasArray:(NSArray *)datasArray selectArray:(NSArray *)selectArray
{
    NSMutableArray *existArray = [NSMutableArray array];
    for (TTDetailStockListModel *model in datasArray) {
        if (model.StockType == 0) {
            [existArray addObject:model];
        }
    }
    
    [_existBtn removeFromSuperview];
    [_customBtn removeFromSuperview];
    
    if (existArray.count > 0) {
        _existBtn = [UIButton createButtonWithTitle:@"现货" titleColor:UIColorHex(333333) titleFont:[UIFont systemFontOfSize:14] backgroundColor:[UIColor whiteColor] target:self action:@selector(existBtnClick:)];
        _existBtn.layer.cornerRadius = 5;
        _existBtn.frame = CGRectMake(0, 0, 75, 30);
        [self.view addSubview:_existBtn];
    }
    if (self.customCount > 0) {
        UIColor *bgColor = _existBtn ? UIColorHex(EDEDED) : [UIColor whiteColor];
        _customBtn = [UIButton createButtonWithTitle:@"下单" titleColor:UIColorHex(333333) titleFont:[UIFont systemFontOfSize:14] backgroundColor:bgColor target:self action:@selector(customBtnClick:)];
        _customBtn.layer.cornerRadius = 5;
        _customBtn.frame = CGRectMake(_existBtn.right + 1, 0, 75, 30);
        [self.view addSubview:_customBtn];
    }
    
    CGFloat dingzhiLeft = _customBtn == nil ? _existBtn.right : _customBtn.right;
    _dingzhiBtn = [UIButton createButtonWithTitle:@"定制" titleColor:UIColorHex(333333) titleFont:[UIFont systemFontOfSize:14] backgroundColor:UIColorHex(EDEDED) target:self action:@selector(dingzhiBtnClick:)];
    _dingzhiBtn.layer.cornerRadius = 5;
    _dingzhiBtn.frame = CGRectMake(dingzhiLeft + 1, 0, 75, 30);
    [self.view addSubview:_dingzhiBtn];
    
    
//    top = 0;
//    if (self.customCount > 0 && existArray.count > 0) {
//        _existBtn = [UIButton createButtonWithTitle:@"现货" titleColor:UIColorHex(333333) titleFont:[UIFont systemFontOfSize:14] backgroundColor:[UIColor whiteColor] target:self action:@selector(existBtnClick:)];
//        _existBtn.layer.cornerRadius = 5;
//        _existBtn.frame = CGRectMake(0, 0, 75, 30);
//        [self.view addSubview:_existBtn];
//
//        _customBtn = [UIButton createButtonWithTitle:@"下单" titleColor:UIColorHex(333333) titleFont:[UIFont systemFontOfSize:14] backgroundColor:UIColorHex(EDEDED) target:self action:@selector(customBtnClick:)];
//        _customBtn.layer.cornerRadius = 5;
//        _customBtn.frame = CGRectMake(_existBtn.right + 1, 0, 75, 30);
//        [self.view addSubview:_customBtn];
//
//    }
    top = 27;
    
    [self.existView removeFromSuperview];
    if (existArray.count > 0) {
        self.existView = [[TTDetailFilterExistView alloc] initWithFrame:CGRectMake(0, top, self.view.width, viewH - top) model:self.model dataArray:existArray];
        self.existView.hidden = existArray.count == 0;
        [self.view addSubview:self.existView];
    }
    
    
    [self.customView removeFromSuperview];
    if (self.customCount > 0) {
        NSMutableArray *array = [NSMutableArray array];
        for (TTDetailStockListModel *model in selectArray) {
            if (model.selected && model.StockType == 2) {
                [array addObject:model];
            }
        }
        CGFloat left = existArray.count > 0 ? self.view.width : 0;
        self.customView = [[TTDetailFliterCustomView alloc] initWithFrame:CGRectMake(left, top, self.view.width, viewH - top) model:self.model styleLibraryId:self.styleLibraryId selectArray:array];
        self.customView.hidden = existArray.count > 0;
        [self.view addSubview:_customView];
    }
    
    CGFloat dingzhiViewLeft = self.customView == nil ? _existView.right : _customView.right;
    self.dingzhiView = [[TTDetailFilterDingzhiView alloc] initWithFrame:CGRectMake(dingzhiViewLeft, top, self.view.width, viewH - top) model:self.model styleLibraryId:self.styleLibraryId];
    [self.view addSubview:self.dingzhiView];
    
    
    BOOL notShowYellowView = (self.allShopShow || existArray.count == 0 || self.stockFilterCount == 0);
    CGFloat footerH = notShowYellowView ? 45 : 75;
    self.footerView = [[UIView alloc] initWithFrame:CGRectMake(0, h - footerH - Tabbar_Bottom_height, self.view.width, footerH + Tabbar_Bottom_height)];
    self.footerView.backgroundColor = kMainColor;
    [self.footerView removeFromSuperview];
    [self.view addSubview:self.footerView];
    
    self.yellowView = [[UIView alloc] initWithFrame:CGRectMake(0, 0, self.view.width, 30)];
    self.yellowView.backgroundColor = UIColorHex(#FCCA59);
    [self.footerView addSubview:self.yellowView];
    
    NSString *title = [NSString stringWithFormat:@"已根据搜索过滤%d件现货，显示全部", self.stockFilterCount];
    NSMutableAttributedString *attrTitle = [[NSMutableAttributedString alloc] initWithString:title];
    [attrTitle addAttributes:@{NSForegroundColorAttributeName : UIColorHex(#FE7575), NSUnderlineStyleAttributeName : @1} range:[title rangeOfString:@"显示全部"]];
    UIButton *allShowBtn = [UIButton buttonWithType:UIButtonTypeCustom];
    allShowBtn.titleLabel.font = [UIFont systemFontOfSize:11];
    [allShowBtn setTitleColor:UIColorHex(#666666) forState:UIControlStateNormal];
    [allShowBtn setAttributedTitle:attrTitle forState:UIControlStateNormal];
    [allShowBtn addTarget:self action:@selector(showAllShopAction:) forControlEvents:UIControlEventTouchUpInside];
    [self.yellowView addSubview:allShowBtn];
    [allShowBtn mas_makeConstraints:^(MASConstraintMaker *make) {
        make.left.mas_equalTo(10);
        make.top.height.equalTo(self.yellowView);
    }];
    
    self.yellowView.hidden = notShowYellowView;
    
    CGFloat confirmBtnTop = notShowYellowView ? 0 : self.yellowView.bottom;
    self.confirmBtn = [UIButton createButtonWithTitle:@"确定" titleColor:[UIColor whiteColor] titleFont:[UIFont systemFontOfSize:18] backgroundColor:nil target:self action:@selector(confirmBtnClick)];
    self.confirmBtn.frame = CGRectMake(0, confirmBtnTop, self.view.width, 45);
    [self.confirmBtn removeFromSuperview];
    [self.footerView addSubview:self.confirmBtn];
    
    if (self.existView == nil && self.customView == nil) {
        [self.confirmBtn setTitle:@"提交" forState:UIControlStateNormal];
    }
    
    if (self.selectDZ && (self.existView || self.customView)) {
        [self dingzhiBtnClick:self.dingzhiBtn];
    }
    
}

- (NSMutableDictionary *)existViewSelectDic
{
    if (!_existViewSelectDic) {
        _existViewSelectDic = [NSMutableDictionary dictionary];
    }
    return _existViewSelectDic;
}



- (void)dealloc
{
    NSLog(@"[< %@ >] --> 释放了", self.className);
    [[NSNotificationCenter defaultCenter] removeObserver:self];
}

@end
